package cn.edu.scau.dormitory_management_system.util;

import cn.edu.scau.dormitory_management_system.constant.FilePath;
import cn.edu.scau.dormitory_management_system.exception.pojo.MyException;
import cn.edu.scau.dormitory_management_system.enums.ExceptionMsgEnum;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author djc
 * @date 2021/8/8
 * @time 15:59
 */
public class ZipUtil {
    private static final List<String> zipNames;

    static {
        File zipFile = new File(FilePath.ZIP_PATH);
        if(!zipFile.exists()) {
            zipFile.mkdir();
        }
        zipNames = new ArrayList<>();
        zipNames.addAll(Arrays.asList("账单汇总.zip", "学生信息汇总.zip",
                "宿舍信息汇总.zip", "学生信息汇总.zip", "宿舍信息汇总.zip"));
    }

    public static String getZipName(int op) {
        return zipNames.get(op);
    }

    public static void zipCompress(String inputPath, String outputPath) {
        try {
            ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(outputPath));
            BufferedOutputStream bos = new BufferedOutputStream(zipOutputStream);

            compress(zipOutputStream, bos, new File(inputPath), null);

            bos.close();
            zipOutputStream.close();
        } catch (Exception e) {
            FileUtil.deleteFile(FilePath.TEMP_PATH);
            FileUtil.deleteFile(FilePath.ZIP_PATH);
            throw new MyException(ExceptionMsgEnum.COMPRESS_ERROR);
        }
    }

    private static void compress(ZipOutputStream out, BufferedOutputStream bos,
                                 File file, String fileName) throws Exception {
        if(fileName == null) {
            fileName = file.getName();
        }

        if(file.isDirectory()) {
            File[] files = file.listFiles();
            if(files.length == 0) {
                out.putNextEntry(new ZipEntry("/"));
            }else {
                for (File subFile : files) {
                    compress(out, bos, subFile,
                            fileName + File.separator + subFile.getName());
                }
            }
        }else {
            out.putNextEntry(new ZipEntry(fileName));
            FileInputStream fos = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fos);
            int len;
            byte[] buf = new byte[1024 * 10];
            while ((len = bis.read(buf)) != -1) {
                bos.write(buf, 0, len);
            }
            bos.flush();
            bis.close();
            fos.close();
        }
    }
}
